﻿using QNote.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;

namespace QNote.Services
{
    internal class JsonSerializeService : ISerializationService
    {
        private readonly string fileName = "note.json";

        public Note? Deserialize()
        {
            if (!File.Exists(fileName))
            {
                return default;
            }
            using FileStream stream = File.OpenRead(fileName);
            try
            {
                return JsonSerializer.Deserialize<Note>(stream);
            }
            catch (Exception)
            {
                return default;
            }          
            //return DeserializeAsync(stream).Result;
        }

        public bool Serialize(Note note)
        {
            using FileStream stream = File.Open(fileName, FileMode.Create);
            //return SerializeAsync(note, stream).Result;
            try
            {
                JsonSerializer.Serialize<Note>(stream, note);
            }
            catch (Exception)
            {
                return false;
            }    
            return true;
        }

        private async Task<bool> SerializeAsync(Note note, FileStream stream)
        {
            try
            {
                await JsonSerializer.SerializeAsync(stream, note);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        private async Task<Note?> DeserializeAsync(FileStream stream)
        {
            try
            {
                return await JsonSerializer.DeserializeAsync<Note>(stream);
            }
            catch (Exception)
            {
                return new Note(string.Empty); ;
            }
        }
    }
}
